package com.pactera.madp.cp.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.data.tenant.TenantContextHolder;
import com.pactera.madp.cp.api.dto.medium.MediumAddDTO;
import com.pactera.madp.cp.api.dto.medium.MediumUpdateDTO;
import com.pactera.madp.cp.api.em.medium.TypeEnum;
import com.pactera.madp.cp.api.entity.BaseEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.entity.greeting.GreetingEntity;
import com.pactera.madp.cp.api.entity.medium.MediumEnyity;
import com.pactera.madp.cp.api.entity.medium.MediumGroupDepartmentEntity;
import com.pactera.madp.cp.api.entity.medium.MediumGroupEntity;
import com.pactera.madp.cp.api.page.SubPage;
import com.pactera.madp.cp.api.vo.ParseLinkArticleVO;
import com.pactera.madp.cp.api.vo.medium.MediumTypeVO;
import com.pactera.madp.cp.api.vo.medium.MediumVO;
import com.pactera.madp.cp.api.vo.medium.MediumWeChatVO;
import com.pactera.madp.cp.common.config.FileUploadConfig;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.common.util.ali.AliyunOssUtils;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.medium.MediumMapper;
import com.pactera.madp.cp.service.IMediumService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:媒体库
 * @author: Huayu
 * @time: 2020/12/4 18:44
 */
@Service
@Slf4j
public class MediumServiceImpl extends ServiceImpl<MediumMapper, MediumEnyity> implements IMediumService {

    @Autowired
    private MediumGroupDepartmentServiceImpl mediumGroupDepartmentService;
    @Autowired
    private MediumGroupServiceImpl mediumGroupService;
    @Autowired
    private WorkEmployeeServiceImpl workEmployeeService;
    @Autowired
    private FileUploadConfig fileUploadConfig;

    @Autowired
    private GreetingServiceImpl greetingService;

    /**
     *
     *
     * @description:
     * @return:
     * @author: Huayu
     * @time: 2020/12/6 9:30
     */
    @Override
    public MediumEnyity getMediumById(Integer id) {
        MediumEnyity mediumEnyity = this.baseMapper.selectOne(Wrappers.<MediumEnyity>lambdaQuery()
                .eq(MediumEnyity::getCorpId, CorpContextHolder.getCorpId())
                .eq(MediumEnyity::getId, id)
                .eq(MediumEnyity::getIsSync,1));
        if(mediumEnyity != null){
            mediumEnyity.setContent(addFullPath(mediumEnyity.getContent(),mediumEnyity.getType()));
        }
        return  mediumEnyity;
    }

    @Override
    public String addFullPath(String content,Integer type){
        JSONObject js = JSON.parseObject(content);
        switch (type){
            case 2:
                js.put("imageFullPath", AliyunOssUtils.getUrl(js.getString("imagePath")));
                break;
            case 3:
                js.put("imageFullPath", AliyunOssUtils.getUrl(js.getString("imagePath")));
                break;
            case 4:
                js.put("voiceFullPath", AliyunOssUtils.getUrl(js.getString("voicePath")));
                break;
            case 5:
                js.put("videoFullPath",AliyunOssUtils.getUrl(js.getString("videoPath")));
                break;
            case 6:
                js.put("imageFullPath",AliyunOssUtils.getUrl(js.getString("imagePath")));
                break;
            case 7:
                js.put("fileFullPath",AliyunOssUtils.getUrl(js.getString("imagePath")));
                break;
        }
        return js.toString();
    }

    /**
     *
     *
     * @description: 添加素材库
     * @return:
     * @author: Huayu
     * @time: 2020/12/7 13:58
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer createMedium(MediumEnyity mediumEnyity) {
        Integer i = this.baseMapper.insert(mediumEnyity);
        return i;
    }

    /**
     *
     *
     * @description: 删除素材库
     * @return:
     * @author: Huayu
     * @time: 2020/12/7 14:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMedium(Integer id) {
        List<GreetingEntity> one = greetingService.list(
                Wrappers.<GreetingEntity>lambdaQuery().eq(GreetingEntity::getMediumId, id)
        );
        if (!one.isEmpty()) {
            throw new CheckedException("该话术已被引用");
        }
        Integer i = this.baseMapper.deleteById(id);
        return i == 1;
    }

    @Override
    public Page getMediumList(String mediumGroupId, String searchStr, Integer type, Page page){
        Integer corpId = CorpContextHolder.getCorpId();

        QueryWrapper<MediumEnyity> wrapper = new QueryWrapper<>();
        wrapper.eq("corp_id",corpId);
        wrapper.eq("is_sync",1);
        if (!StrUtil.isBlank(searchStr)){
            wrapper.like("content",searchStr);
        }
        if (!StrUtil.isBlank(mediumGroupId)){
            wrapper.eq("medium_group_id",Integer.valueOf(mediumGroupId));
        }
        if (type != null && !type.equals(0)){
            wrapper.eq("type",type);
        }
        wrapper.orderByDesc("create_time");
        return (Page) page(page, wrapper);
    }

    @Override
    public Page getMediumList1(List<String> mediumGroupIds, String searchStr, Integer type, Page page){
        Integer corpId = CorpContextHolder.getCorpId();

        QueryWrapper<MediumEnyity> wrapper = new QueryWrapper<>();
        if (mediumGroupIds != null && mediumGroupIds.size() > 0) {
            wrapper.in("medium_group_id", mediumGroupIds);
        } else {
            return new Page();
        }
        wrapper.eq("corp_id",corpId);
        wrapper.eq("is_sync",1);
        if (!StrUtil.isBlank(searchStr)){
            wrapper.like("content",searchStr);
        }
        if (type != null && !type.equals(0)){
            wrapper.eq("type",type);
        }
        wrapper.orderByDesc("create_time");
        return (Page) page(page, wrapper);
    }

    /**
     * 话术分页
     * @param mediumGroupId
     * @param searchStr
     * @param type
     * @param page
     * @return
     */
    @Override
    public Page<List<MediumVO>> mediumPage(String mediumGroupId, String searchStr, Integer type, Page page) {
        if(type == null) {
            type = 0;
        }
        List<String> mediumGroupIds = new ArrayList<>();
        if (!StringUtil.isBlank(mediumGroupId))
        if (!Integer.valueOf(mediumGroupId).equals(0)){
            mediumGroupIds.add(mediumGroupId);
            List<String> mediumGroupIds1 = mediumGroupService.list(
                    Wrappers.<MediumGroupEntity>lambdaQuery()
                    .select(MediumGroupEntity::getId)
                    .eq(MediumGroupEntity::getParentId, mediumGroupId)
            ).stream().map(MediumGroupEntity::getId).map(s -> String.valueOf(s)).collect(Collectors.toList());
            if (!ObjectUtil.isEmpty(mediumGroupIds1)) {
                mediumGroupIds.addAll(mediumGroupIds1);
            }
        }
        page = this.getMediumList1(mediumGroupIds, searchStr, type, page);
        List<MediumEnyity> mediumList= page.getRecords();
        List<MediumVO> mediumVOS = new LinkedList<>();
        for (MediumEnyity m:mediumList) {
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            MediumVO mediumVO = new MediumVO();
            mediumVO.setId(m.getId());
            mediumVO.setTypeDesc(TypeEnum.getTypeByCode(m.getType()));
            mediumVO.setType(m.getType());
            mediumVO.setCollectionTitle(m.getCollectionTitle());
//            mediumVO.setContent(JSONArray.parseArray(m.getContent()));
            mediumVO.setContent(m.getContent());
            mediumVO.setUserId(m.getUserId());
            mediumVO.setUsername(m.getUserName());
            mediumVO.setMediumGroupId(m.getMediumGroupId());
            if (m.getMediumGroupId() == 0){
                mediumVO.setMediumGroupName("全部分组");
            } else {
                mediumVO.setMediumGroupName(mediumGroupService.getOne(Wrappers.<MediumGroupEntity>lambdaQuery()
                        .eq(MediumGroupEntity::getId, m.getMediumGroupId()))
                        .getName());
            }
            mediumVO.setCreateTime(pattern.format(m.getCreateTime()));
            mediumVOS.add(mediumVO);
        }

        //分页参数
        page.setRecords(mediumVOS);
        return page;
    }

    @Override
    public IPage mediumPageWeChat(String searchStr, Integer type, String wxUserId, String mediumGroupId, Page page) {
        Integer corpId = CorpContextHolder.getCorpId();
        WorkEmployeeEntity one = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                .eq(WorkEmployeeEntity::getWxUserId, wxUserId)
                .eq(WorkEmployeeEntity::getCorpId, corpId));
        Integer departmentId = one.getMainDepartmentId();
        IPage results = null;

        if (StringUtil.isBlank(mediumGroupId) || Integer.valueOf(mediumGroupId) == 0) {

//            page = (Page) this.page(page, Wrappers.<MediumEnyity>lambdaQuery()
//                    .eq(MediumEnyity::getCorpId, CorpContextHolder.getCorpId())
//                    .eq(BaseEntity::getTenantId, TenantContextHolder.getTenantId())
//                    .eq(MediumEnyity::getIsSync,1)
//                    .orderByDesc(BaseEntity::getCreateTime));
            Integer tenantId = TenantContextHolder.getTenantId();
            results = this.baseMapper.getMediumPage(page, corpId, tenantId, 1, departmentId, type);
        } else {
            List<String> mediumGroupIds = new ArrayList<>();
            mediumGroupIds.add(mediumGroupId);
            List<String> mediumGroupIds1 = mediumGroupService.list(
                    Wrappers.<MediumGroupEntity>lambdaQuery()
                            .select(MediumGroupEntity::getId)
                            .eq(MediumGroupEntity::getParentId, mediumGroupId)
            ).stream().map(MediumGroupEntity::getId).map(s -> String.valueOf(s)).collect(Collectors.toList());
            if (!ObjectUtil.isEmpty(mediumGroupIds1)) {
                mediumGroupIds.addAll(mediumGroupIds1);
            }
            LambdaQueryWrapper<MediumEnyity> wrapper = Wrappers.<MediumEnyity>lambdaQuery()
                    .in(MediumEnyity::getMediumGroupId, mediumGroupIds)
                    .eq(MediumEnyity::getCorpId,CorpContextHolder.getCorpId())
                    .eq(BaseEntity::getTenantId,TenantContextHolder.getTenantId())
                    .eq(MediumEnyity::getIsSync,1)
                    .eq(MediumEnyity::getType, type)
                    .orderByDesc(BaseEntity::getCreateTime);
            if (searchStr != null && !searchStr.isEmpty()) {
                wrapper.like(MediumEnyity::getContent, searchStr);
            }
            results = this.page(page, wrapper);
        }
        List<MediumEnyity> mediumList = results.getRecords();
        List<MediumVO> mediumVOS = new LinkedList<>();
        for (MediumEnyity m : mediumList) {
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            MediumVO mediumVO = new MediumVO();
            mediumVO.setId(m.getId());
            mediumVO.setTypeDesc(TypeEnum.getTypeByCode(m.getType()));
            mediumVO.setType(m.getType());
            mediumVO.setCollectionTitle(m.getCollectionTitle());
//            mediumVO.setContent(JSONArray.parseArray(m.getContent()));
            mediumVO.setContent(m.getContent());
            mediumVO.setUserId(m.getUserId());
            mediumVO.setUsername(m.getUserName());
            mediumVO.setMediumGroupId(m.getMediumGroupId());
            if (m.getMediumGroupId() == 0) {
                mediumVO.setMediumGroupName("全部分组");
            } else {
                mediumVO.setMediumGroupName(mediumGroupService.getOne(Wrappers.<MediumGroupEntity>lambdaQuery()
                        .eq(MediumGroupEntity::getId, m.getMediumGroupId()))
                        .getName());
            }
            mediumVO.setCreateTime(pattern.format(m.getCreateTime()));
            mediumVOS.add(mediumVO);
        }

        //分页参数
        results.setRecords(mediumVOS);
        return results;
    }

    /**
     *
     *
     * @description: 移动分组
     * @return:
     * @author: Huayu
     * @time: 2020/12/7 14:55addFullPath
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMediumById(MediumEnyity mediumEnyity) {
        return  this.updateById(mediumEnyity);
    }

    /**
     * 修改话术信息
     * @param dto
     * @return
     */
    @Override
    public boolean updateMediumByIds(MediumUpdateDTO dto) {
        MediumEnyity enyity = new MediumEnyity();
        JSON json = (JSON)JSONObject.toJSON(dto.getReplyList());

        if (dto.getReplyList().size()>1){
            enyity.setType(7);
        }else {
            String s = json.toString();
            String strip = StringUtils.strip(s, "[]");
            JSONObject jsonObject = JSONObject.parseObject(strip);
            enyity.setType(Integer.valueOf(Integer.valueOf(jsonObject.get("type").toString())));
        }
        enyity.setUserName(dto.getUserName());
        enyity.setContent(json.toJSONString());
        enyity.setMediumGroupId(dto.getMediumGroupId());
        enyity.setCorpId(CorpContextHolder.getCorpId());
        enyity.setUserId(AccountService.getUserId());
        enyity.setCollectionTitle(dto.getCollectionTitle());
        enyity.setId(dto.getId());
        enyity.setMediumGroupId(dto.getMediumGroupId());
        boolean b = updateById(enyity);
        if (b){
         return saveMediumMediaIdById(enyity.getId());
        }else {
            return false;
        }

    }

    @Override
    public boolean update(MediumUpdateDTO dto) {
        MediumEnyity entity = new MediumEnyity();
        entity.setType(dto.getType());
        entity.setUserName(dto.getUserName());
        entity.setContent(dto.getContent());
        entity.setMediumGroupId(dto.getMediumGroupId());
        entity.setCorpId(CorpContextHolder.getCorpId());
        entity.setUserId(AccountService.getUserId());
        entity.setCollectionTitle(dto.getCollectionTitle());
        entity.setId(dto.getId());
        return updateById(entity);
    }

    @Override
    public MediumVO mediumShow(Integer id) {
        MediumEnyity medium = baseMapper.selectOne(Wrappers.<MediumEnyity>lambdaQuery()
                .eq(MediumEnyity::getCorpId, CorpContextHolder.getCorpId())
                .eq(MediumEnyity::getId, id)
                .eq(MediumEnyity::getIsSync,1));
        MediumVO mediumVO = new MediumVO();
        if (medium == null){
            return mediumVO;
        }
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        mediumVO.setId(medium.getId());
        mediumVO.setTypeDesc(TypeEnum.getTypeByCode(medium.getType()));
        mediumVO.setType(medium.getType());
        mediumVO.setCollectionTitle(medium.getCollectionTitle());
//            mediumVO.setContent(JSONArray.parseArray(medium.getContent()));
        mediumVO.setContent(medium.getContent());
        mediumVO.setUserId(medium.getUserId());
        mediumVO.setUsername(medium.getUserName());
        mediumVO.setMediumGroupId(medium.getMediumGroupId());
        if (medium.getMediumGroupId() == 0) {
            mediumVO.setMediumGroupName("全部分组");
        } else {
            mediumVO.setMediumGroupName(mediumGroupService.getOne(Wrappers.<MediumGroupEntity>lambdaQuery()
                    .eq(MediumGroupEntity::getId, medium.getMediumGroupId()))
                    .getName());
        }
        mediumVO.setCreateTime(pattern.format(medium.getCreateTime()));
        return mediumVO;
    }

    @Override
    public Integer updateMediaByGroupId(Integer id, int mediumGroupId) {
        MediumEnyity mediumEnyity = new MediumEnyity();
        mediumEnyity.setId(id);
        mediumEnyity.setMediumGroupId(mediumGroupId);
        Integer i = this.baseMapper.updateMediaByGroupId(mediumEnyity);
        return i;
    }

    @Override
    public List<MediumEnyity> mediumListByDept(Integer id) {
        List<MediumGroupDepartmentEntity> entities = mediumGroupDepartmentService.list(
                Wrappers.<MediumGroupDepartmentEntity>lambdaQuery().eq(MediumGroupDepartmentEntity::getDeptId, id));
        List<MediumEnyity> enyities = new LinkedList<>();
        entities.forEach(e ->{
            List<MediumEnyity> list = this.list(Wrappers.<MediumEnyity>lambdaQuery()
                    .eq(MediumEnyity::getMediumGroupId, e.getMediumGroupId())
                    .eq(MediumEnyity::getCorpId,CorpContextHolder.getCorpId())
                    .eq(BaseEntity::getTenantId,TenantContextHolder.getTenantId())
                    .eq(MediumEnyity::getIsSync,1));
            list.forEach(l ->{
                enyities.add(l);
            });
        });

        return enyities;
    }


    @Override
    public boolean insertAllBatch(MediumAddDTO dto) {
        MediumEnyity enyity = new MediumEnyity();
        JSON json = (JSON)JSONObject.toJSON(dto.getReplyList());
        if (dto.getReplyList().size()>1){
            enyity.setType(7);
        }else {
            String s = json.toString();
            String strip = StringUtils.strip(s, "[]");
            JSONObject jsonObject = JSONObject.parseObject(strip);
            enyity.setType(Integer.valueOf(Integer.valueOf(jsonObject.get("type").toString())));
        }
        enyity.setUserName(dto.getUserName());
        enyity.setContent(json.toJSONString());
        enyity.setMediumGroupId(dto.getMediumGroupId());
        enyity.setCorpId(CorpContextHolder.getCorpId());
        enyity.setUserId(AccountService.getUserId());
        enyity.setCollectionTitle(dto.getCollectionTitle());
        enyity.setCreateTime(DateUtil.toLocalDateTime(new Date()));
        if (dto.getIsSync() != null){
            enyity.setIsSync(dto.getIsSync());
        }
        if (this.save(enyity)){
            if (saveMediumMediaIdById(enyity.getId())){
                return true;
            }else {
                removeById(enyity.getId());
                throw new CheckedException("临时素材上传失败，请检查上传素材是否符合");
            }
        }else {
            return false;
        }

    }

    @Override
    public boolean insert(MediumAddDTO dto) {
        MediumEnyity entity = new MediumEnyity();
        entity.setType(dto.getType());
        entity.setUserName(dto.getUserName());
        entity.setContent(dto.getContent());
        entity.setMediumGroupId(dto.getMediumGroupId());
        entity.setCorpId(CorpContextHolder.getCorpId());
        entity.setUserId(AccountService.getUserId());
        entity.setCollectionTitle(dto.getCollectionTitle());
        entity.setCreateTime(DateUtil.toLocalDateTime(new Date()));
        return this.save(entity);
    }

    @Override
    public R insertByGreeting(MediumAddDTO dto) {
        MediumEnyity enyity = new MediumEnyity();
        JSON json = (JSON)JSONObject.toJSON(dto.getReplyList());
        if (dto.getReplyList().size()>1){
            enyity.setType(7);
        }else {
            String s = json.toString();
            String strip = StringUtils.strip(s, "[]");
            JSONObject jsonObject = JSONObject.parseObject(strip);
            enyity.setType(Integer.valueOf(Integer.valueOf(jsonObject.get("type").toString())));
        }
        enyity.setUserName(dto.getUserName());
        enyity.setContent(json.toJSONString());
        enyity.setMediumGroupId(dto.getMediumGroupId());
        enyity.setCorpId(CorpContextHolder.getCorpId());
        enyity.setUserId(AccountService.getUserId());
        enyity.setCollectionTitle(dto.getCollectionTitle());
        enyity.setCreateTime(DateUtil.toLocalDateTime(new Date()));
        if (dto.getIsSync() != null){
            enyity.setIsSync(dto.getIsSync());
        }
        boolean save = this.save(enyity);
        if (save){
            if (enyity.getIsSync() ==1){
                boolean b = saveMediumMediaIdById(enyity.getId());
                if (b){
                    return R.ok(enyity.getId());
                }else {
                    removeById(enyity.getId());
                    return R.failed("新增素材失败，请检查素材格式");
                }
            }else {
                return R.ok(enyity.getId());
            }

        }
        return R.failed("新增失败");
    }

    @Override
    public boolean insertAllBatchWeChat(MediumAddDTO dto) {
        MediumEnyity enyity = new MediumEnyity();
        JSON json = (JSON)JSONObject.toJSON(dto.getReplyList());

        String s = json.toString();
        String strip = StringUtils.strip(s, "[]");
        JSONObject jsonObject = JSONObject.parseObject(strip);
        enyity.setType(Integer.valueOf(Integer.valueOf(jsonObject.get("type").toString())));

        WorkEmployeeEntity one = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                .eq(WorkEmployeeEntity::getWxUserId, dto.getWxUserId())
                .eq(WorkEmployeeEntity::getCorpId,CorpContextHolder.getCorpId()));
        enyity.setUserName(one.getName());
        enyity.setContent(json.toJSONString());
        enyity.setMediumGroupId(dto.getMediumGroupId());
        enyity.setCorpId(one.getCorpId());
        enyity.setUserId(one.getLogUserId());
        enyity.setCollectionTitle(dto.getCollectionTitle());
        if (dto.getIsSync() != null){
            enyity.setIsSync(dto.getIsSync());
        }
        return this.save(enyity);
    }

    @Override
    public ParseLinkArticleVO getParseLinkArticle(String url) {
        ParseLinkArticleVO parseLinkArticleVO = new ParseLinkArticleVO();
        try {
            Connection.Response response = Jsoup.connect(url)
                    .userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
                    .timeout(10000)
                    .execute(); //获取当前url状态信息
            if (response.statusCode() == 200){ //当状态值为200时
                Document document = Jsoup.connect(url).get();//获取当前url网页信息
                String imgUrl = null;
                Elements img = document.select("body img"); //获取当前url网页中图片的列表信息
                if (img.isEmpty()){
                    url = "http://mf.dev.pactera-fintech.com:7442/mfs/da0292fd9d2d40cf89a652d602965eeb.png";
                }else {
                    String attr = img.get(0).attr("src"); //获取图片信息的地址
                    String[] split = attr.split(":");
                    if (split[0].toLowerCase().equals("http")  || split[0].toLowerCase().equals("https")){ //判断图片地址前是否有http或者https头部
                        imgUrl = attr;
                    }else {
                        imgUrl = "http:"+attr; //如果没有则添加
                    }
                }
                String title = document.title(); //获取网页标题
                Elements select = document.select("meta[name=description]"); //获取网页description信息列表
                if (select.isEmpty()){
                    parseLinkArticleVO.setDescription(url);//当description为空时则返回
                }else {
                    parseLinkArticleVO.setDescription(select.get(0).attr("content"));//当description列表不为空时则获取content的值
                }
                parseLinkArticleVO.setStatusCode(response.statusCode());//写入当前url状态值
                parseLinkArticleVO.setStatusMessage(response.statusMessage());
                if (StringUtil.isBlank(title)){
                    parseLinkArticleVO.setTitle("链接");
                }else {
                    parseLinkArticleVO.setTitle(title);
                }
                parseLinkArticleVO.setImgUrl(imgUrl);
                parseLinkArticleVO.setSuccess(true);
                parseLinkArticleVO.setLink(url);
            }else {
                parseLinkArticleVO.setStatusCode(response.statusCode());//写入当前url状态值
                parseLinkArticleVO.setStatusMessage(response.statusMessage());
                parseLinkArticleVO.setSuccess(false);
            }
        } catch (IOException e) {
            parseLinkArticleVO.setTitle("链接");
            parseLinkArticleVO.setImgUrl(fileUploadConfig.getRealPath() + File.separator +"mfs/94a90d6a4b274d738dad36b9355784c8.png");
            parseLinkArticleVO.setLink(url);
            parseLinkArticleVO.setTitle("链接");
            parseLinkArticleVO.setDescription(url);
            parseLinkArticleVO.setStatusCode(200);
            e.printStackTrace();
        }
        return parseLinkArticleVO;
    }

    @Override
    public R sendMedium(Integer id) {
        MediumEnyity medium = getOne(Wrappers.<MediumEnyity>lambdaQuery().eq(MediumEnyity::getId, id)
                .eq(MediumEnyity::getCorpId, CorpContextHolder.getCorpId()).eq(MediumEnyity::getIsSync, 1));
        String mediaId = medium.getMediaId();
        if (medium == null || StringUtils.isBlank(mediaId)){
            saveMediumMediaIdById(id);
            MediumEnyity enyity = getOne(Wrappers.<MediumEnyity>lambdaQuery().eq(MediumEnyity::getId, id)
                    .eq(MediumEnyity::getCorpId, CorpContextHolder.getCorpId()).eq(MediumEnyity::getIsSync, 1));
            mediaId = enyity.getMediaId();
        }
        JSONArray array = JSONArray.parseArray(mediaId);
        return R.ok(array);
    }

    @Override
    public Page<List<MediumTypeVO>> mediumPageByType(Integer type, Page page,Integer mediumGroupId,String search) {
        Page list;
        if (mediumGroupId == null){
            list = getMediumList(null, search, type, page);
        }else {
            list = getMediumList(String.valueOf(mediumGroupId), search, type, page);
        }

        List<MediumEnyity> records = list.getRecords();
        List<MediumTypeVO> typeVOS = new LinkedList<>();
        for (MediumEnyity m:records) {
            MediumTypeVO typeVO = new MediumTypeVO();
            typeVO.setId(m.getId());
            typeVO.setType(m.getType());
            typeVO.setTypeDesc(TypeEnum.getTypeByCode(m.getType()));
            typeVO.setContent(JSONArray.parseArray(m.getContent()));
            typeVOS.add(typeVO);
        }
        SubPage subPage = new SubPage();
        subPage.setPages(page.getPages());
        subPage.setTotal(page.getTotal());
        subPage.setSize(page.getSize());
        subPage.setRecords(typeVOS);
        subPage.setCurrent(page.getCurrent());
        return subPage;
    }

    @Override
    public void saveMediumMediaId() {
        List<MediumEnyity> list = list(
                Wrappers.<MediumEnyity>lambdaQuery()
                .eq(MediumEnyity::getIsSync, 1)
                .ne(MediumEnyity::getType, 1)
                .eq(MediumEnyity::getCorpId,CorpContextHolder.getCorpId())
        );
        for (MediumEnyity medium:list) {
            String content = medium.getContent();
            JSONArray objects = JSONArray.parseArray(content);
            List<MediumWeChatVO> chatVOS = new LinkedList<>();
            for (int i = 0; i < objects.size(); i++) {
                MediumWeChatVO chatVO = new MediumWeChatVO();
                JSONObject jsonObject = JSONObject.parseObject(objects.get(i).toString());

                Integer type = jsonObject.getInteger("type");
                if (type == 2 || type == 4 || type == 5){
                    chatVO.setType(type);
                    chatVO.setTypeText(TypeEnum.getTypeByCode(type));

                    String types = null;
                    switch (type){
                        case 2:
                            types = "image";
                            break;
                        case 4:
                            types = "file";
                            break;
                        case 5:
                            types = "video";
                            break;
                    }
                    JSONObject object = JSONObject.parseObject(jsonObject.getString("content"));
                    String url = object.getString("url");
                    String[] split = url.split("/");
                    String fileUrl = fileUploadConfig.getRealPath() + File.separator + "/medium/corp-"+CorpContextHolder.getCorpId()+"/"+split[split.length-1];
                    File file = new File(fileUrl);
                    log.info("开始上传临时素材");
                    String  s;
                    try {
                        log.info("文件名为："+file.getName());
                        s = WxApiUtils.uploadImageToTemps(medium.getCorpId(), file,types);
                    }catch (NullPointerException e){
                        log.info("临时素材库已有素材，无法上传");
                        continue;
                    }
                    chatVO.setMediaId(s);
                    chatVOS.add(chatVO);
                }
                MediumEnyity enyity = new MediumEnyity();
                enyity.setMediaId(JSONUtil.toJsonStr(chatVOS));
                enyity.setId(medium.getId());
                updateMediumById(enyity);
            }
        }
    }

    @Override
    public boolean saveMediumMediaIdById(Integer id) {
        boolean flag = false;
        MediumEnyity medium = getOne(Wrappers.<MediumEnyity>lambdaQuery().eq(MediumEnyity::getId, id));
        String content = medium.getContent();
            JSONArray objects = JSONArray.parseArray(content);
            List<MediumWeChatVO> chatVOS = new LinkedList<>();
            for (int i = 0; i < objects.size(); i++) {
                MediumWeChatVO chatVO = new MediumWeChatVO();
                JSONObject jsonObject = JSONObject.parseObject(objects.get(i).toString());

                Integer type = jsonObject.getInteger("type");
                if (type == 2 || type == 4 || type == 5){
                    chatVO.setType(type);
                    chatVO.setTypeText(TypeEnum.getTypeByCode(type));

                    String types = null;
                    switch (type){
                        case 2:
                            types = "image";
                            break;
                        case 4:
                            types = "file";
                            break;
                        case 5:
                            types = "video";
                            break;
                    }
                    JSONObject object = JSONObject.parseObject(jsonObject.getString("content"));
                    String url = object.getString("url");
                    String[] split = url.split("/");
                    String fileUrl = fileUploadConfig.getRealPath() + File.separator + "/medium/corp-"+CorpContextHolder.getCorpId()+"/"+split[split.length-1];
                    File file = new File(fileUrl);
                    log.info("开始上传临时素材");
                    String  s;
                    try {
                        log.info("文件名为："+file.getName());
                        s = WxApiUtils.uploadImageToTemps(medium.getCorpId(), file,types);

                    }catch (NullPointerException e){
                        log.info("临时素材库已有素材，无法上传");
                        continue;
                    }
                    if (StrUtil.isBlank(s)){
                        return false;
                    }
                    chatVO.setMediaId(s);
                    chatVOS.add(chatVO);
                }
                MediumEnyity enyity = new MediumEnyity();
                enyity.setMediaId(JSONUtil.toJsonStr(chatVOS));
                enyity.setId(medium.getId());
                flag = updateMediumById(enyity);
        }
        return flag;
    }

}
